﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Messaging;
using System.Text;

namespace SimpleServiceBus.Endpoints.Msmq
{
    public static class MsmqHelper
    {
        public static bool QueueExists(string queueName)
        {
            queueName = String.Format(@".\Private$\{0}", queueName);

            return MessageQueue.Exists(queueName);
        }

        public static bool QueueIsTransactional(string queueName)
        {
            queueName = String.Format(@".\Private$\{0}", queueName);

            using (MessageQueue queue = new MessageQueue(queueName))
            {
                return queue.Transactional;
            }
        }

        public static void EnsureQueue(string queueName, bool transactional)
        {
            queueName = String.Format(@".\Private$\{0}", queueName);


            if (!MessageQueue.Exists(queueName))
            {
                MessageQueue.Create(queueName, transactional);
            }
        }

        public static void EnsureQueue(string queueName)
        {
            EnsureQueue(queueName, true);
        }

        public static int GetPendingMessageForQueue(string queueFormatName)
        {
            var qMgmt = new MSMQ.MSMQManagementClass();
            object machine = Environment.MachineName;
            object missing = Type.Missing;
            object formatName = queueFormatName;

            qMgmt.Init(ref machine, ref missing, ref formatName);
            return qMgmt.MessageCount;
        }
    }
}
